function init() {
    addimg.src = picsrc1;
    addimghover.src = picsrc2;
    findimg.src = findpicsrc1;
    findimghover.src = findpicsrc2;
    shareimg.src = sharepicsrc1;
    shareimghover.src = sharepicsrc2;

    addimgBtn.showTip("新建笔记");
    findimgBtn.showTip("查找笔记");
    shareimgBtn.showTip("分享笔记");

    s1.innerHTML = currentUser.tel;
}
//1.初始化页面，主要给页面的层或图片赋值
init();

var isLoad = false;
var isover = false;
var p = 0;
var firstNewDiv;
var currentBiJi;

function loadData() {

    if (!isLoad && !isover) {
        p++;
        console.log(p);
        loading2.style.display = "block";
        isLoad = true;//数据正在被加载，在isload等于false之前不接受新的请求
        var currentUser = JSON.parse(localStorage.currentUser)
        ajax("/biji/all2", {"page": p, "size": 10, "sortNum": 1,"params":[],uid:currentUser.id,
            token:currentUser.token},
            function (data) {
                //d2.innerHTML = "";
                setTimeout(function () {
                    var totalPages = data.totalPages;
                    data = data.content;

                    if (p == totalPages) {
                        isover = true;
                        d3.innerHTML = "我也是有底线的！"
                    }
                    //data = data.reverse();//[1,2,3]==>[3,2,1]

                    for (let i = 0; i < data.length; i++) {
                        // 创建笔记层
                        var newDiv = document.createElement("div");
                        newDiv.id = "biji"+data[i].id;

                        if(i==0&&!firstNewDiv){
                            firstNewDiv = newDiv;
                        }

                        newDiv.onclick = function(){
                          newDivClick(data[i]);
                        };
                        newDiv.className = "biji clearfix";

                        // 创建左侧层
                        var leftDiv = document.createElement("div");
                        leftDiv.className = "left fl";

                        // 创建标题层，并解决长度过长的问题
                        var titleDiv = document.createElement("div");
                        titleDiv.className = "biji_title";
                        var titleTxt = data[i].title;
                        if (titleTxt) {
                            titleDiv.innerHTML = titleTxt.length < 15 ? titleTxt : titleTxt.substring(0, 15) + "...";
                            leftDiv.appendChild(titleDiv);
                        }
                        // 创建标题层结束

                        // 创建时间层，并解决时间显示问题
                        var dateDiv = document.createElement("div");
                        dateDiv.className = "biji_date";
                        var createdate = data[i].createDate;
                        if (createdate) {
                            var arr = createdate.split(/[\/: ]/);

                            if (arr.length == 6) {
                                // console.log(arr);
                                //new Date(年,月,日，时，分，秒）
								var amorpm = arr[3].substring(0,2);
								var h = arr[3].substring(2);
								if(amorpm=="下午"){
									h = parseInt(h) + 12;
								}
								if(h==24) h = 12;
                                var time1 = new Date(arr[0], arr[1] - 1, arr[2], h,
                                    arr[4], arr[5]).getTime();
                                var time2 = new Date().getTime();
                                var diff = time2 - time1; // 秒 分 时 天 月 年

                                if (diff < 0) {
                                    dateDiv.innerHTML = "时空穿越";
                                } else if (diff < 5 * 1000) {
                                    dateDiv.innerHTML = "刚刚";
                                } else if (diff < 60 * 1000) {
                                    dateDiv.innerHTML = Math.floor(diff / 1000) + " 秒前";
                                } else if (diff < 60 * 60 * 1000) {
                                    dateDiv.innerHTML = Math.floor(diff / (1000 * 60)) + " 分钟前";
                                } else if (diff < 60 * 60 * 1000 * 24) {
                                    dateDiv.innerHTML = Math.floor(diff / (1000 * 60 * 60)) + " 小时前";
                                } else if (diff < 60 * 60 * 1000 * 24 * 30) {
                                    dateDiv.innerHTML = Math.floor(diff / (1000 * 60 * 60 * 24)) + " 天前";
                                } else if (diff < 60 * 60 * 1000 * 24 * 30 * 365) {
                                    dateDiv.innerHTML = Math.floor(diff / (1000 * 60 * 60 * 24 * 30)) + " 月前";
                                } else if (diff < 60 * 60 * 1000 * 24 * 30 * 365 * 100) {
                                    dateDiv.innerHTML = Math.floor(diff / (1000 * 60 * 60 * 24 * 30 * 365)) + " 年前";
                                }

                                leftDiv.appendChild(dateDiv);
                            }
                        }
                        // 创建时间层结束

                        // 创建内容层，并解决长度过长的问题和HTML显示问题
                        var contentDiv = document.createElement("div");
                        contentDiv.className = "biji_content";
                        var cnt = data[i].content;
                        var txt = data[i].contextTxt;

                        if (!txt) {
                            txt = cnt;
                        }
                        contentDiv.innerHTML = txt.length < 30 ? txt : txt.substring(0, 30) + "...";
                        leftDiv.appendChild(contentDiv);
                        // 创建内容层结束

                        newDiv.appendChild(leftDiv);
                        // 创建左侧层结束

                        // 创建右侧层
                        var rightDiv = document.createElement("div");
                        rightDiv.className = "right fl";

                        // 如果右图片，将右测的层的背景设置为该图片，并保证图片寸尺合理
                        if (cnt.indexOf("<img") != -1) {
                            var start = cnt.indexOf("<img");//383 538
                            var end = cnt.indexOf(">", start);
                            var imgHTML = cnt.substring(start, end + 1);
                            var start2 = imgHTML.indexOf("src=\"");
                            var end2 = imgHTML.indexOf("\"", start2 + 5);
                            var picsrc = imgHTML.substring(start2 + 5, end2);
                            rightDiv.style.background = "url(" + picsrc + ") no-repeat center center";
                            rightDiv.style.backgroundSize = "cover";
                            newDiv.appendChild(rightDiv);
                        } else {
                            leftDiv.style.width = "100%";
                        }
                        // 创建右测层结束

                        // 创建删除按钮
                        var deleteEle = document.createElement("button");
                        deleteEle.innerHTML = "删除";
                        deleteEle.style.display = "block";
                        deleteEle.style.clear = "both";

                        deleteEle.onclick = function (e) {
                            deleteBiJi(data[i].id,e);
                        };
                        newDiv.appendChild(deleteEle);
                        // 创建删除按钮结束

                        // 创建笔记层结束
                        d2.appendChild(newDiv);
                    }
                    if(document.getElementById("loading2")) {
                        loading2.style.display = "none";//和20行呼应
                    }
                    isLoad = false;


                }, 100);
            })
    }
}

//2.加载所有笔记数据
loadData();

//当页面滚动时
//防抖和节流
window.onscroll = function () {
    var sh = document.documentElement.scrollHeight;
    var ch = document.documentElement.clientHeight;
    var st = document.documentElement.scrollTop ||
        document.body.scrollTop;

    if (sh < st + ch + 100) {
        loadData();
    }
};

//3.增加笔记按钮
addimgBtn.onclick = function () {
    d1.style.display = "none";
    addDiv.style.display = "block";
    addOrUpdate.innerHTML = "新增";
    title.value = "";
    content.innerHTML = "";
    contentTip.style.display = "block";
    title.focus();
}

//4.保存笔记按钮
finishBtn.onclick = function () {
    loading.style.display = "block";
    var titleValue = title.value;
    var contentValue = content.innerHTML;
    var contextTxt = content.innerText.trim();

    if (titleValue.length == 0 || contentValue.length == 0) {
        alert("请填写内容");
        title.focus();//获得焦点
        return;
    }

    var param = {
        "biJiUser": {
            "id": currentUser.id
        },
        "content": contentValue,
        "createDate": new Date().toLocaleString(),
        "title": titleValue,
        "contextTxt": contextTxt
    };

    if(addOrUpdate.innerHTML=="编辑"){
        param.id = currentBiJi.id;
        param.createDate = currentBiJi.createDate;
    }
    ajax("/biji/add",param , function (data) {
        if (data) {
            //setTimeout(function(){
            d1.style.display = "block";
            addDiv.style.display = "none";
            loading.style.display = "none";
            title.value = "";
            content.innerHTML = "";
            //loadData();
            var addNewDiv;
            if(!firstNewDiv) {
                addNewDiv = moban.cloneNode(true);
                addNewDiv.style.display = "block";
            }else{
                addNewDiv = firstNewDiv.cloneNode(true);
            }
            addNewDiv.getElementsByClassName("biji_title")
                [0].innerHTML = titleValue;
            if(addOrUpdate.innerHTML=="编辑"){
                var currentNewDiv = document.
                getElementById("biji"+currentBiJi.id);

                addNewDiv.getElementsByClassName("biji_date")
                    [0].innerHTML =
                    currentNewDiv.getElementsByClassName("biji_date")
                    [0].innerHTML;
            }else {
                addNewDiv.getElementsByClassName("biji_date")
                    [0].innerHTML = "刚刚";
            }
            var txt = data.contextTxt;
            addNewDiv.getElementsByClassName("biji_content")
                [0].innerHTML = txt.length>30
                ?txt.substring(0,30)+"...":txt;
            addNewDiv.id = "biji"+data.id;

            addNewDiv.onclick = function(){
                newDivClick(data);
            };

            addNewDiv.getElementsByTagName("button")[0]
                .onclick = function(e){
                deleteBiJi(data.id,e);
            };

            var cnt = data.content;

            var rightDiv = addNewDiv.getElementsByClassName("right")[0];
            var leftDiv = addNewDiv.getElementsByClassName("left")[0];

            if (cnt.indexOf("<img") != -1) {
                if(!rightDiv) {
                    rightDiv = document.createElement("div");
                    rightDiv.className = "right fl";
                }
                leftDiv.style.width = "70%";
                rightDiv.style.width = "30%";
                var start = cnt.indexOf("<img");//383 538
                var end = cnt.indexOf(">", start);
                var imgHTML = cnt.substring(start, end + 1);
                var start2 = imgHTML.indexOf("src=\"");
                var end2 = imgHTML.indexOf("\"", start2 + 5);
                var picsrc = imgHTML.substring(start2 + 5, end2);
                rightDiv.style.background = "url(" + picsrc + ") no-repeat center center";
                rightDiv.style.backgroundSize = "cover";
                var btn = addNewDiv.getElementsByTagName("button")[0];
                addNewDiv.insertBefore(rightDiv,btn);
            } else {
                if(rightDiv){
                    addNewDiv.removeChild(rightDiv);
                }
                leftDiv.style.width = "100%";
            }

            if(addOrUpdate.innerHTML=="编辑"){

                currentNewDiv.innerHTML = addNewDiv.innerHTML;

                currentNewDiv.getElementsByTagName("button")[0]
                    .onclick = function(e){
                    deleteBiJi(data.id,e);
                };

                currentNewDiv.onclick = function(){
                    newDivClick(data);
                };

            }else {
                d2.insertBefore(addNewDiv, firstNewDiv);
                firstNewDiv = addNewDiv;
            }
            //alert(d2.innerHTML);
            //},3000);

            document.documentElement.scrollTop = st;
        }
    });


}

//5.返回按钮
returnBtn.onclick = function () {
    d1.style.display = "block";
    addDiv.style.display = "none";
    document.documentElement.scrollTop = st;
}

//6.内容文本框提示设置
content.onfocus = function () {
    contentTip.style.display = "none";
}
content.onblur = function () {
    if (content.innerHTML.length == 0) {
        contentTip.style.display = "block";
    }
}

//7.删除笔记
function deleteBiJi(id,e) {
    if (confirm("确定要删除这个笔记？")) {
        ajax("/biji/del", {id: id}, function (data) {
            if (data) {
                //loadData();
                var biji = document.getElementById("biji"+id);

                if(biji.id==firstNewDiv.id){
                    var nextBiJi = biji.nextElementSibling;
                    firstNewDiv = nextBiJi;
                }
                d2.removeChild(biji);
            } else {
                alert("删除失败！")
            }
        });
    }
    if(e.stopPropagation) {
        e.stopPropagation();//停止事件向上冒泡，不要触发上层事件
    }else {
        e.cancelBubble = true; //IE,兼容处理
    }
}

var st;
//8.具体内容显示和编辑
function newDivClick(data){
    st = document.documentElement.scrollTop;
    console.log(data);
    d1.style.display = "none";
    addDiv.style.display = "block";
    title.value = data.title;
    content.innerHTML = data.content;
    contentTip.style.display = "none";
    document.documentElement.scrollTop = 0;
    addOrUpdate.innerHTML = "编辑";
    currentBiJi = data;
}

//9.分享
shareBtn.onclick = function(){
    window.open('http://service.weibo.com/share/share.php?appkey=583395093&title='+
        currentBiJi.title+'&url=http://47.105.49.194:8088/biji2/index.html');
}

//10.退出
logout.onclick = function(){
  localStorage.clear();
  location = "login.html";
};

//11.保存为图片
saveAsPic.onclick = function(){
	var imgs = content.getElementsByTagName("img");
	for(var i=0;i<imgs.length;i++){
		imgs[i].setAttribute("crossorigin","anonymous");
	}
	html2canvas(content,{width:content.clientWidth,height:content.scrollHeight,useCORS:true}).then(function(canvas) {
		//console.log(canvas.toDataURL());
		// 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = title.value+".png";
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    //var blob = new Blob([content]);
    eleLink.href = canvas.toDataURL();
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
		
		});
};